﻿//===============================================================================
// Copyright © 2011 Allen Lee
// This code released under the terms of the MIT License (http://iridescent.codeplex.com/license)
//===============================================================================
using System;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Practices.Prism.Interactivity;

namespace Iridescent
{
    public class AppBarButtonUpdateSource : Behavior<PhoneApplicationPage>
	{
		public AppBarButtonUpdateSource()
		{
			// Insert code required on object creation below this point.

			//
			// The line of code below sets up the relationship between the command and the function
			// to call. Uncomment the below line and add a reference to Microsoft.Expression.Interactions
			// if you choose to use the commented out version of MyFunction and MyCommand instead of
			// creating your own implementation.
			//
			// The documentation will provide you with an example of a simple command implementation
			// you can use instead of using ActionCommand and referencing the Interactions assembly.
			//
			//this.MyCommand = new ActionCommand(this.MyFunction);
		}

		protected override void OnAttached()
		{
			base.OnAttached();

			// Insert code that you would want run when the Behavior is attached to an object.

            _button = AssociatedObject.ApplicationBar.FindButton(ButtonText);
            if (_button != null)
            {
                _button.Click += ButtonClick;
            }
		}

		protected override void OnDetaching()
		{
			base.OnDetaching();

			// Insert code that you would want run when the Behavior is removed from an object.

            if (_button != null)
            {
                _button.Click -= ButtonClick;
            }
		}

        public string ButtonText { get; set; }

        private ApplicationBarIconButton _button;

        private void ButtonClick(object sender, EventArgs e)
        {
            var focusedTextBox = FocusManager.GetFocusedElement() as TextBox;
            if (focusedTextBox != null)
            {
                focusedTextBox
                    .GetBindingExpression(TextBox.TextProperty)
                    .UpdateSource();
            }
        }

		/*
		public ICommand MyCommand
		{
			get;
			private set;
		}
		 
		private void MyFunction()
		{
			// Insert code that defines what the behavior will do when invoked.
		}
		*/
	}
}